from socket import *

def read_and_filter_lines(filename, Lmin, Lmax):
    with open(filename, 'r') as file:
        lines = file.readlines()
    filtered_lines = [line.strip() for line in lines if Lmin <= len(line.strip()) <= Lmax]
    return filtered_lines

def main(server_ip, server_port):
    # 1.建立TCP连接：
    client_socket = socket(AF_INET, SOCK_STREAM)
    client_socket.connect((server_ip, server_port))

    # 2.读取文件并筛选字符串：
    Lmin = int(input("Lmin(>0)："))
    Lmax = int(input("Lmax(<100)："))
    filename = 'input.txt'  # 替换为你的文件名
    reverse_lines = read_and_filter_lines(filename, Lmin, Lmax)

    # 3.初始化和协议：
    N = len(reverse_lines)  #筛选出符合长度的字符串数量
    if N==0:
        print("没有数据需要传输")
        client_socket.send(f"close".encode())
        client_socket.close()
        print("与server端断开连接")
        return

    Type="01"

    #initialization
    message=f"{Type}{N}"
    client_socket.send(message.encode())
    message = client_socket.recv(1024)
    Type = message[0:2].decode()

    # agreement
    if Type == "02":
        print("连接server成功，开始传输数据")
        # reverseRequest
        number=1
        for line in reverse_lines:
            Type = 3
            length = len(line)
            if length<10:
                b=str(0)#凑字符长度
            elif (length>=10 and length<100):
                b=str(00)
            message=f"0{Type}b{N}{line}".encode()
            client_socket.send(message)

            #reverseAnswer
            message = client_socket.recv(1024)
            Type = message[:2].decode()
            if Type=='04':
                length = int.from_bytes(message[2:6])
                reverse_data = message[6:(6 + length)].decode()
                print(f'{number}:', reverse_data)  # 输出从服务器接收的数据
                number+=1

        client_socket.send(f"close".encode())
        client_socket.close()
        print("与server端断开连接")
    else:
        print("连接失败：server端没有返回agreement报文")

if __name__ == '__main__':
    server_ip = input("server IP：")
    server_port = int(input("server port："))
    main(server_ip, server_port)